import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface UserInfo {
  id: string
  username: string
  name: string
  role: 'super_admin' | 'campus_admin' | 'student' | 'coach'
  avatar?: string
  campus: string
  phone: string
  email: string
  balance?: number // 学员账户余额
  level?: 'senior' | 'middle' | 'junior' // 教练等级
}

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref<UserInfo>({
    id: '',
    username: '',
    name: '',
    role: 'student',
    campus: '',
    phone: '',
    email: ''
  })

  // 登录状态
  const isLoggedIn = ref(false)

  // 权限列表
  const permissions = ref<string[]>([])

  // 登录
  const login = async (user: UserInfo) => {
    userInfo.value = user
    isLoggedIn.value = true
    
    // 根据角色设置权限
    setPermissions(user.role)
    
    // 保存到本地存储
    localStorage.setItem('userInfo', JSON.stringify(user))
    localStorage.setItem('isLoggedIn', 'true')
  }

  // 退出登录
  const logout = () => {
    userInfo.value = {
      id: '',
      username: '',
      name: '',
      role: 'student',
      campus: '',
      phone: '',
      email: ''
    }
    isLoggedIn.value = false
    permissions.value = []
    
    // 清除本地存储
    localStorage.removeItem('userInfo')
    localStorage.removeItem('isLoggedIn')
  }

  // 更新用户信息
  const updateUserInfo = (updates: Partial<UserInfo>) => {
    userInfo.value = { ...userInfo.value, ...updates }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  // 设置权限
  const setPermissions = (role: string) => {
    const rolePermissions: Record<string, string[]> = {
      super_admin: [
        'campus:manage',
        'license:manage',
        'user:view_all',
        'finance:view_all',
        'system:manage'
      ],
      campus_admin: [
        'coach:approve',
        'student:manage',
        'booking:manage',
        'competition:manage',
        'finance:manage',
        'message:send'
      ],
      student: [
        'coach:search',
        'coach:select',
        'booking:create',
        'booking:cancel',
        'review:submit',
        'competition:enroll',
        'finance:recharge'
      ],
      coach: [
        'student:view',
        'booking:confirm',
        'booking:cancel',
        'review:reply',
        'pairing:approve'
      ]
    }
    
    permissions.value = rolePermissions[role] || []
  }

  // 检查权限
  const hasPermission = (permission: string) => {
    return permissions.value.includes(permission)
  }

  // 检查角色
  const hasRole = (role: string | string[]) => {
    if (Array.isArray(role)) {
      return role.includes(userInfo.value.role)
    }
    return userInfo.value.role === role
  }

  // 从本地存储恢复状态
  const restoreFromStorage = () => {
    const savedUserInfo = localStorage.getItem('userInfo')
    const savedLoginStatus = localStorage.getItem('isLoggedIn')
    
    if (savedUserInfo && savedLoginStatus === 'true') {
      try {
        const user = JSON.parse(savedUserInfo)
        userInfo.value = user
        isLoggedIn.value = true
        setPermissions(user.role)
      } catch (error) {
        console.error('恢复用户状态失败:', error)
        logout()
      }
    }
  }

  return {
    userInfo,
    isLoggedIn,
    permissions,
    login,
    logout,
    updateUserInfo,
    hasPermission,
    hasRole,
    restoreFromStorage
  }
})
